package com.xqq.service.weather;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xqq.entity.WeatherDO;
import com.xqq.utils.CommonUtil;
import com.xqq.utils.HttpUtil;
import com.xqq.utils.WeatherConstans;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

import static com.xqq.MqConsumerApplication.convertTimestampToStr;
import static com.xqq.utils.CommonUtil.convertTUCtodatetimeEpoch;

@Slf4j
public class WeatherService {
    //城市天气
    public static List<WeatherDO> getHeFengWeatherNow(String longitude, String latitude, String weatherApiKey) {
        String weatherUrl = "https://devapi.qweather.com/v7/weather/now" +
                "?location=" +
                longitude +
                "," +
                latitude +
                "&key=" +
                weatherApiKey +
                "&lang=zh";
        String weatherResult = "";
        List<WeatherDO> weatherList = new ArrayList<>();
        try {
            weatherResult = HttpUtil.sendGet(weatherUrl, null);
            weatherList = parseHeFengWeatherNow(weatherResult, longitude, latitude);
        } catch (Exception e) {
            log.error("该位置 {},{} 调用解析天气信息失败{}",longitude,latitude,e.getMessage(), e);
        }
        return weatherList;
    }


    //格点天气
    public static List<WeatherDO> getHeFengWeather24H(String longitude, String latitude, String weatherApiKey) {
        String weatherUrl = "https://devapi.qweather.com/v7/grid-weather/24h" +
                "?location=" +
                longitude +
                "," +
                latitude +
                "&key=" +
                weatherApiKey +
                "&lang=zh";
        String weatherResult = "";
        List<WeatherDO> weatherList = new ArrayList<>();
        try {
            weatherResult = HttpUtil.sendGet(weatherUrl, null);
            weatherList = parseHeFengWeather24H(weatherResult, longitude, latitude);
        } catch (Exception e) {
            log.error("该位置 {},{} 调用解析天气信息失败{}",longitude,latitude,e.getMessage(), e);
        }
        return weatherList;
    }

    private static List<WeatherDO> parseHeFengWeather24H(String result, String longitude, String latitude) {
        List<WeatherDO> weathers = new ArrayList<>();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        JSONArray hoursArray = jsonObject.getJSONArray("hourly");
        hoursArray.forEach(hours -> {
            JSONObject hourObj = (JSONObject) hours;
            WeatherDO weatherDO = new WeatherDO();
            long datetimeEpoch = convertTUCtodatetimeEpoch(hourObj.getStr("fxTime"));
            weatherDO.setDatetimeEpoch(datetimeEpoch);
            weatherDO.setDatetime(convertTimestampToStr(datetimeEpoch));
            double temp = hourObj.getDouble("temp", WeatherConstans.DEFALUT_TEMP);
            weatherDO.setTemp(temp);
            double humidity = hourObj.getDouble("humidity", WeatherConstans.DEFALUT_HUMIDITY);
            weatherDO.setHumidity(humidity);
            double precip = hourObj.getDouble("precip", WeatherConstans.DEFALUT_PRECIP);
            weatherDO.setPrecip(precip);
            double windspeed = hourObj.getDouble("windSpeed", WeatherConstans.DEFALUT_WINDSPEED);
            weatherDO.setWindspeed(windspeed);
            double visibility = hourObj.getDouble("vis", WeatherConstans.DEFALUT_VISIBILITY);
            weatherDO.setVisibility(visibility);
            String conditions = hourObj.getStr("text", WeatherConstans.DEFALUT_CONDITIONS_ZH);
            weatherDO.setConditions(conditions);
            weatherDO.setPosition(longitude + "," + latitude);
            weathers.add(weatherDO);
        });
        return weathers;
    }

    private static List<WeatherDO> parseHeFengWeatherNow(String result, String longitude, String latitude) {
        List<WeatherDO> weathers = new ArrayList<>();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        JSONObject nowObj = jsonObject.getJSONObject("now");
        WeatherDO weatherDO = new WeatherDO();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime roundedDown = now.truncatedTo(ChronoUnit.HOURS);
        long datetimeEpoch = roundedDown.atZone(ZoneId.systemDefault()).toEpochSecond();
        weatherDO.setDatetimeEpoch(datetimeEpoch);
        weatherDO.setDatetime(convertTimestampToStr(datetimeEpoch));
        double temp = nowObj.getDouble("temp", WeatherConstans.DEFALUT_TEMP);
        weatherDO.setTemp(temp);
        double humidity = nowObj.getDouble("humidity", WeatherConstans.DEFALUT_HUMIDITY);
        weatherDO.setHumidity(humidity);
        double precip = nowObj.getDouble("precip", WeatherConstans.DEFALUT_PRECIP);
        weatherDO.setPrecip(precip);
        double windspeed = nowObj.getDouble("windSpeed", WeatherConstans.DEFALUT_WINDSPEED);
        weatherDO.setWindspeed(windspeed);
        double visibility = nowObj.getDouble("vis", WeatherConstans.DEFALUT_VISIBILITY);
        weatherDO.setVisibility(visibility);
        String conditions = nowObj.getStr("text", WeatherConstans.DEFALUT_CONDITIONS_ZH);
        weatherDO.setConditions(conditions);
        weatherDO.setPosition(longitude + "," + latitude);
        weathers.add(weatherDO);
        return weathers;
    }

    //获取今日天气
    public static List<WeatherDO> getWeather(String longitude, String latitude, String weatherApiKey) {
        String startDate = CommonUtil.getTodayTime();
        String endDate = CommonUtil.getTodayTime();
        String weatherUrl = "https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/" +
                latitude +
                "%2C%20" +
                longitude +
                "/" +
                startDate +
                "/" +
                endDate +
                "?unitGroup=metric&include=hours&key=" +
                weatherApiKey +
                "&contentType=json";
        String weatherResult = "";
        try {
            weatherResult = HttpUtil.sendGet(weatherUrl, null);
        } catch (Exception e) {
            log.error("调用天气信息失败", e);
        }
        List<WeatherDO> weatherList = parseWeather(weatherResult, longitude, latitude);
        return weatherList;
    }

    private static List<WeatherDO> parseWeather(String result, String longitude, String latitude) {
        List<WeatherDO> weathers = new ArrayList<>();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        JSONArray days = jsonObject.getJSONArray("days");
        days.forEach(day -> {
            JSONObject dayObj = (JSONObject) day;
            dayObj.getJSONArray("hours").forEach(hour -> {
                WeatherDO weatherDO = new WeatherDO();
                JSONObject hourObj = (JSONObject) hour;
                long datetimeEpoch = hourObj.getLong("datetimeEpoch");
                weatherDO.setDatetimeEpoch(datetimeEpoch);
                weatherDO.setDatetime(convertTimestampToStr(datetimeEpoch));
                double temp = hourObj.getDouble("temp", WeatherConstans.DEFALUT_TEMP);
                weatherDO.setTemp(temp);
                double humidity = hourObj.getDouble("humidity", WeatherConstans.DEFALUT_HUMIDITY);
                weatherDO.setHumidity(humidity);
                double precip = hourObj.getDouble("precip", WeatherConstans.DEFALUT_PRECIP);
                weatherDO.setPrecip(precip);
                double snow = hourObj.getDouble("snow", WeatherConstans.DEFALUT_SNOW);
                weatherDO.setSnow(snow);
                double windspeed = hourObj.getDouble("windspeed", WeatherConstans.DEFALUT_WINDSPEED);
                weatherDO.setWindspeed(windspeed);
                double visibility = hourObj.getDouble("visibility", WeatherConstans.DEFALUT_VISIBILITY);
                weatherDO.setVisibility(visibility);
                String conditions = hourObj.getStr("conditions", WeatherConstans.DEFALUT_CONDITIONS);
                weatherDO.setConditions(conditions);
                weatherDO.setPosition(longitude + "," + latitude);
                weathers.add(weatherDO);
            });
        });
        return weathers;
    }
}
